import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 安全的网络图片组件
/// 带有错误处理和占位符
/// 支持网络图片和 base64 格式的 data URI
class SafeNetworkImage extends StatelessWidget {
  final String? imageUrl;
  final double? width;
  final double? height;
  final BoxFit fit;
  final BorderRadius? borderRadius;
  final Widget? placeholder;
  final Widget? errorWidget;

  const SafeNetworkImage({
    super.key,
    required this.imageUrl,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.borderRadius,
    this.placeholder,
    this.errorWidget,
  });

  /// 检查是否为 base64 data URI
  bool _isBase64Image(String url) {
    return url.startsWith('data:image');
  }

  /// 解析 base64 data URI 并返回字节数据
  Uint8List? _parseBase64Image(String dataUri) {
    try {
      // data URI 格式: ...
      final commaIndex = dataUri.indexOf(',');
      if (commaIndex == -1) {
        return null;
      }
      final base64String = dataUri.substring(commaIndex + 1);
      return base64Decode(base64String);
    } catch (e) {
      print('Base64 图片解析失败: $e');
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果URL为空或无效，显示默认错误组件
    if (imageUrl == null || imageUrl!.trim().isEmpty) {
      return _buildErrorWidget();
    }

    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        borderRadius: borderRadius,
        color: const Color(0xFFF5F5F5),
      ),
      child: ClipRRect(
        borderRadius: borderRadius ?? BorderRadius.zero,
        child: _isBase64Image(imageUrl!)
            ? _buildBase64Image()
            : _buildNetworkImage(),
      ),
    );
  }

  /// 构建 base64 图片
  Widget _buildBase64Image() {
    final bytes = _parseBase64Image(imageUrl!);
    if (bytes == null) {
      return errorWidget ?? _buildErrorWidget();
    }

    return Image.memory(
      bytes,
      width: width,
      height: height,
      fit: fit,
      errorBuilder: (context, error, stackTrace) {
        print('Base64 图片加载失败: $error');
        return errorWidget ?? _buildErrorWidget();
      },
    );
  }

  /// 构建网络图片
  Widget _buildNetworkImage() {
    return Image.network(
      imageUrl!,
      width: width,
      height: height,
      fit: fit,
      // 加载中的占位符
      loadingBuilder: (context, child, loadingProgress) {
        if (loadingProgress == null) {
          return child;
        }
        return placeholder ?? _buildLoadingWidget();
      },
      // 错误处理
      errorBuilder: (context, error, stackTrace) {
        print('图片加载失败: $imageUrl, 错误: $error');
        return errorWidget ?? _buildErrorWidget();
      },
    );
  }

  /// 构建加载中的占位符
  Widget _buildLoadingWidget() {
    return Container(
      width: width,
      height: height,
      color: const Color(0xFFF5F5F5),
      child: Center(
        child: SizedBox(
          width: 20.w,
          height: 20.w,
          child: CircularProgressIndicator(
            strokeWidth: 2.w,
            valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFF4A90E2)),
          ),
        ),
      ),
    );
  }

  /// 构建错误占位符
  Widget _buildErrorWidget() {
    return Container(
      width: width,
      height: height,
      color: const Color(0xFFF5F5F5),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.image_not_supported_outlined,
              size: (width != null && width! < 100) ? 20.w : 32.w,
              color: const Color(0xFFCCCCCC),
            ),
            if (height == null || height! > 60.h) ...[
              SizedBox(height: 8.h),
              Text(
                '图片加载失败',
                style: TextStyle(
                  fontSize: 20.sp,
                  color: const Color(0xFF999999),
                ),
                textAlign: TextAlign.center,
              ),
            ],
          ],
        ),
      ),
    );
  }
}

/// 带有播放按钮的安全网络图片组件
/// 专门用于设备缩略图显示
class SafeNetworkImageWithPlay extends StatelessWidget {
  final String? imageUrl;
  final double width;
  final double height;
  final BorderRadius? borderRadius;
  final VoidCallback? onTap;

  const SafeNetworkImageWithPlay({
    super.key,
    required this.imageUrl,
    required this.width,
    required this.height,
    this.borderRadius,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: width,
        height: height,
        decoration: BoxDecoration(
          borderRadius: borderRadius,
          color: const Color(0xFFF0F0F0),
        ),
        child: Stack(
          children: [
            // 背景图片
            SafeNetworkImage(
              imageUrl: imageUrl,
              width: width,
              height: height,
              fit: BoxFit.cover,
              borderRadius: borderRadius,
            ),
            // 播放按钮覆盖层
            Center(
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                width: 44.w,
                height: 44.h,
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.6),
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withValues(alpha: 0.3),
                      offset: const Offset(0, 2),
                      blurRadius: 8,
                    ),
                  ],
                ),
                child: Icon(Icons.play_arrow, color: Colors.white, size: 24.w),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
